package com.tvshows.structure.reader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import sun.net.www.protocol.http.HttpURLConnection;

import com.tvshows.structure.reader.exception.TimeOutAtteintException;

public class RssReader
{

    private static final Logger LOGGER = Logger.getLogger( RssReader.class );

    private static final String URL_RSS = "http://ezrss.it/search/index.php?";

    private static final String QUALITY_720P = "720P";

    private String showName;

    private String dateSchedule;

    /**
     * Constructor
     */
    public RssReader()
    {

    }

    /**
     * Read links for the show name
     * 
     * @param showName the given show
     * @throws XMLStreamException
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws TimeOutAtteintException
     */
    public String readRss( String showName )
        throws XMLStreamException, SAXException, IOException, ParserConfigurationException, TimeOutAtteintException
    {
        dateSchedule = new SimpleDateFormat( "yyyy-MM-dd" ).format( Calendar.getInstance().getTime() );
        this.showName = showName;
        String torrentTarget = null;

        LOGGER.info( "récupération des torrents disponible sur le rss pour la série " + showName );

        InputStream in = read();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse( in );

        NodeList items = doc.getElementsByTagName( "item" );

        if ( items.getLength() > 0 )
        {
            if ( items.getLength() == 1 )
            {
                return getValue( (Element) items.item( 0 ), "link" );
            }
            for ( int i = 0; i < items.getLength(); i++ )
            {
                Element item = (Element) items.item( i );
                LOGGER.debug( item.getTextContent() );
                if ( !( getValue( item, "title" ).contains( QUALITY_720P ) ) )
                {
                    return getValue( item, "link" );
                }
            }
        }

        return torrentTarget;
    }

    /**
     * Gets the value of an element
     * 
     * @param parent parent node
     * @param nodeName name of the node
     * @return value of the node
     */
    public String getValue( Element parent, String nodeName )
    {
        return parent.getElementsByTagName( nodeName ).item( 0 ).getFirstChild().getNodeValue();
    }

    /**
     * @return the read url
     * @throws TimeOutAtteintException
     */
    private InputStream read()
        throws TimeOutAtteintException
    {
        String finalUrl = URL_RSS + "show_name=" + showName + "&date=" + dateSchedule + "&mode=rss";
        LOGGER.debug( finalUrl );
        try
        {
            URL url = new URL( finalUrl );
            URLConnection conn = new HttpURLConnection( url, null );
            conn.setReadTimeout( 5000 );
            conn.setConnectTimeout( 5000 );
            conn.connect();
            return conn.getInputStream();
        }
        catch ( IOException e )
        {
            throw new TimeOutAtteintException( "Timeout dépassé" );
        }
    }
}
